<?php
/** 
 * Copyright (c) 2012, Jiehun.com.cn Inc. All Rights Reserved
 * @author Ronnie(dengxiaolong@jiehun.com.cn)
 * @date 2012-3-2
 * @version 1.0 
 * @brief 
 *  
 **/
class Worksheet
{
	private $_schema;
	
	private $rowCount = 0;
	
	public function getHeader($sheet='Sheet1')
	{
		$size = count($this->_schema);
		return <<<CODE
<Worksheet ss:Name="{$sheet}">
  <Table x:FullColumns="1"
   x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="13.5">
   <Column ss:AutoFitWidth="0" ss:Width="153.75" ss:Span="2"/>
CODE;
	}
	
	public function setSchema($schema)
	{
		foreach($schema as $key=>$value)
		{
			$this->_schema[$key] = $value;
		}
	}
	
	public function getSchema()
	{
		$codes = array('<Row>');
		foreach($this->_schema as $key=>$info) {
			$type = $this->getSchemaType($info);
			if (is_string($info)) {
				$name = $info;
			} else {
				$name = isset($info['name']) ? $info['name'] : $key;
			}
			$codes[] = "<Cell ss:StyleID=\"s16\"><Data ss:Type=\"{$type}\">{$name}</Data></Cell>";
		}
		$codes[] = '</Row>';
		return implode("\n", $codes);
	}
	
	public function getRow($row)
	{
		$codes = array('<Row>');
		foreach($this->_schema as $key=>$info) {
			$type = $this->getSchemaType($info);
			
			if (isset($row[$key])) {
				$data = $this->formatData($row[$key]);
				$codes[] = "<Cell ss:StyleID=\"s17\"><Data ss:Type=\"{$type}\">{$data}</Data></Cell>";
			} else {
				$codes[] = "<Cell ss:StyleID=\"s17\"/>";
			}
		}
		$codes[] = '</Row>';
		return implode("\n", $codes);
	}
	
	private function formatData($data)
	{
		$data = str_replace('&nbsp;', ' ', $data);
		$data = preg_replace(array('/</', '/>/', '/&/', '/\'/', '/"/'), array('&lt;', '&gt;', '&amp;', '&apos;', '&quot;'), $data);
		return $data;
	}
	
	private function getSchemaType($info)
	{
		if (is_string($info)) {
			$type = 'String';
		} else {
			$type = isset($info['type']) ? $info['type'] : 'String';
		}
		return $type;
	}
	
	public function getFooter()
	{
		return <<<CODE
</Table>
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <PageSetup>
    <Header x:Margin="0.3"/>
    <Footer x:Margin="0.3"/>
    <PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/>
   </PageSetup>
   <Print>
    <ValidPrinterInfo/>
    <PaperSizeIndex>9</PaperSizeIndex>
    <HorizontalResolution>600</HorizontalResolution>
    <VerticalResolution>600</VerticalResolution>
   </Print>
   <Selected/>
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
CODE;
	}
}
